<!--
 * @Author: ZhaoZhiqi
 * @Date: 2022-08-09 09:47:21
 * @LastEditors: ZhaoZhiqi
 * @LastEditTime: 2022-08-09 11:20:04
 * @Description: TableCell, table中多文本td组件
 
 * @Param {String} content 文本内容
 * @Param {Number} maxLines 最大行数
 * @Param {Boolean} canCopy 是否开启点击文本复制功能

 * @FilePath: \tuanfeng-admin-front\src\components\TableCell.vue
-->
<script setup lang="ts">
import { toRefs } from "vue";
import { ElMessage } from "element-plus";

const props = defineProps({
    content: {
        type: String,
        required: true,
    },
    maxLines: {
        type: Number,
        default: 1,
    },
    canCopy: {
        type: Boolean,
        default: false,
    },
});

const { content, maxLines, canCopy } = toRefs(props);

// 计算多行省略类名
const getClassName = () => {
    let str = `ellipsis_${maxLines.value}`;
    if (canCopy.value) str += " copy";
    return str;
};

// 复制粘贴
function copyToClipboard(s) {
    try {
        if (window.clipboardData) {
            window.clipboardData.setData("text", s);
        } else {
            (function (s) {
                document.oncopy = function (e) {
                    e.clipboardData.setData("text", s);
                    e.preventDefault();
                    document.oncopy = null;
                };
            })(s);
            document.execCommand("Copy");
        }
        return true;
    } catch (e) {
        return false;
    }
}

// 复制
const copy = () => {
    if (canCopy.value) {
        const res = copyToClipboard(content.value);
        if (res) {
            ElMessage({
                message: "复制成功",
                type: "success",
            });
        } else {
            ElMessage({
                message: "复制失败",
                type: "error",
            });
        }
    }
};
</script>
<template>
    <el-tooltip class="tooltip" :show-after="600" effect="dark" :content="content" placement="top-start">
        <div :class="getClassName()" @click="copy">{{ content }}</div>
    </el-tooltip>
</template>
<style scoped lang="less">
@import url("../assets/less/common.less");

.copy {
    cursor: pointer;
    &:hover {
        text-decoration: underline;
    }
}
</style>